package com.dms.modules.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.merchant.service.MerchantService;
import com.dms.modules.product.dto.ProductSpecDTO;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.ProductSpecTemplate;
import com.dms.modules.product.entity.ProductCategory;
import com.dms.modules.product.mapper.ProductSpecTemplateMapper;
import com.dms.modules.product.service.ProductCategoryService;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.product.service.ProductSpecTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSpecTemplateServiceImpl extends ServiceImpl<ProductSpecTemplateMapper, ProductSpecTemplate> implements ProductSpecTemplateService {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService categoryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveSpecTemplate(ProductSpecDTO specDTO) {
        // 检查同一分类下是否存在相同名称的规格模板
        checkDuplicateName(specDTO.getCategoryId(), specDTO.getName(), null);
        
        // 获取当前商家ID
        Long merchantId = getCurrentMerchantId();
        
        // 检查分类是否属于当前商家
        checkCategoryBelongsToMerchant(specDTO.getCategoryId(), merchantId);
        
        ProductSpecTemplate template = new ProductSpecTemplate();
        BeanUtils.copyProperties(specDTO, template);
        save(template);
        return template.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSpecTemplate(ProductSpecDTO specDTO) {
        if (specDTO.getId() == null) {
            throw new BusinessException("规格模板ID不能为空");
        }
        
        // 获取当前商家ID
        Long merchantId = getCurrentMerchantId();
        
        // 检查规格模板是否存在
        ProductSpecTemplate template = getById(specDTO.getId());
        if (template == null) {
            throw new BusinessException("规格模板不存在");
        }
        
        // 检查分类是否属于当前商家
        checkCategoryBelongsToMerchant(template.getCategoryId(), merchantId);
        
        // 检查同一分类下是否存在相同名称的规格模板（排除自身）
        checkDuplicateName(specDTO.getCategoryId(), specDTO.getName(), specDTO.getId());
        
        BeanUtils.copyProperties(specDTO, template);
        updateById(template);
    }

    @Override
    public List<ProductSpecTemplate> listByCategoryId(Long categoryId) {
        log.debug("Fetching spec templates for categoryId: {}", categoryId);
        
        LambdaQueryWrapper<ProductSpecTemplate> wrapper = new LambdaQueryWrapper<ProductSpecTemplate>();
        
        // 如果没有指定分类ID，获取所有可用分类的规格模板
        if (categoryId == null) {
            // 获取当前商家ID
            Long merchantId = getCurrentMerchantId();
            
            // 获取商家的所有商品分类ID
            List<Long> categoryIds = productService.list(new LambdaQueryWrapper<Product>()
                    .eq(Product::getMerchantId, merchantId)
                    .select(Product::getCategoryId))
                    .stream()
                    .map(Product::getCategoryId)
                    .distinct()
                    .collect(Collectors.toList());
            
            // 如果商家还没有商品，返回所有可用分类的规格模板
            if (categoryIds.isEmpty()) {
                List<ProductCategory> availableCategories = categoryService.list(new LambdaQueryWrapper<ProductCategory>()
                        .eq(ProductCategory::getVisible, 1));
                categoryIds = availableCategories.stream()
                        .map(ProductCategory::getId)
                        .collect(Collectors.toList());
            }
            
            if (!categoryIds.isEmpty()) {
                wrapper.in(ProductSpecTemplate::getCategoryId, categoryIds);
            }
        } else {
            wrapper.eq(ProductSpecTemplate::getCategoryId, categoryId);
        }
        
        wrapper.eq(ProductSpecTemplate::getDeleted, false)
               .orderByAsc(ProductSpecTemplate::getSort);
        
        List<ProductSpecTemplate> templates = list(wrapper);
        log.debug("Found {} spec templates", templates.size());
        
        return templates;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSpecTemplate(Long id) {
        // 获取当前商家ID
        Long merchantId = getCurrentMerchantId();
        
        ProductSpecTemplate template = getById(id);
        if (template == null) {
            throw new BusinessException("规格模板不存在");
        }
        
        // 检查分类是否属于当前商家
        checkCategoryBelongsToMerchant(template.getCategoryId(), merchantId);
        
        // 使用 MyBatis-Plus 的逻辑删除功能
        removeById(id);
    }

    @Override
    public List<ProductSpecTemplate> listByMerchantId(Long merchantId, Long categoryId) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 构建查询条件
        LambdaQueryWrapper<ProductSpecTemplate> wrapper = new LambdaQueryWrapper<ProductSpecTemplate>()
                .eq(ProductSpecTemplate::getMerchantId, merchantId)
                .eq(categoryId != null, ProductSpecTemplate::getCategoryId, categoryId)  // 如果categoryId不为空，则添加分类过滤
                .eq(ProductSpecTemplate::getDeleted, false)
                .orderByAsc(ProductSpecTemplate::getSort);
                
        return list(wrapper);
    }

    private void checkDuplicateName(Long categoryId, String name, Long excludeId) {
        LambdaQueryWrapper<ProductSpecTemplate> queryWrapper = new LambdaQueryWrapper<ProductSpecTemplate>()
                .eq(ProductSpecTemplate::getCategoryId, categoryId)
                .eq(ProductSpecTemplate::getName, name)
                .eq(ProductSpecTemplate::getDeleted, false);
        
        if (excludeId != null) {
            queryWrapper.ne(ProductSpecTemplate::getId, excludeId);
        }
        
        if (count(queryWrapper) > 0) {
            throw new BusinessException("该分类下已存在相同名称的规格模板");
        }
    }

    private Long getCurrentMerchantId() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }
        return merchantService.getByUserId(userId).getId();
    }

    private void checkCategoryBelongsToMerchant(Long categoryId, Long merchantId) {
        // 检查分类是否存在
        if (categoryId == null) {
            throw new BusinessException("分类ID不能为空");
        }
        
        // 检查分类是否存在且可用
        ProductCategory category = categoryService.getById(categoryId);
        if (category == null) {
            throw new BusinessException("商品分类不存在");
        }
        
        // 检查分类是否可见
        if (category.getVisible() != null && category.getVisible() == 0) {
            throw new BusinessException("该分类不可用");
        }
    }

    /**
     * 用于存储当前请求的分类ID
     */
    private static class ProductSpecContext {
        private static final ThreadLocal<Long> currentCategoryId = new ThreadLocal<>();
        
        public static void setCurrentCategoryId(Long categoryId) {
            currentCategoryId.set(categoryId);
        }
        
        public static Long getCurrentCategoryId() {
            return currentCategoryId.get();
        }
        
        public static void clear() {
            currentCategoryId.remove();
        }
    }
} 